package cn.net.mugui.net.task;

import java.util.LinkedList;

import com.mugui.base.base.Autowired;
import com.mugui.base.base.Component;
import com.mugui.base.client.net.auto.AutoTask;
import com.mugui.base.client.net.base.Task;
import com.mugui.base.client.net.base.TaskInterface;
import com.mugui.base.util.Other;

import cn.net.mugui.net.dao.Dao;
import cn.net.mugui.net.p2p.Server;
import cn.net.mugui.net.p2p.ServerAttr;
import cn.net.mugui.net.p2p.ServerManager;
import cn.net.mugui.net.task.PerHandleTask.PerHandleType;

/**
 * 等待连接的处理任务
 *
 * @author 木鬼
 */
@AutoTask
@Task(time = 0)
@Component
public class WaitConnectionTask implements TaskInterface {

    private final LinkedList<String> linkedList = new LinkedList<String>();
    @Autowired
    private ServerManager serverManager;
    @Autowired
    private Server server;
    @Autowired
    private Dao dao;

    public void init() {
        System.out.println(WaitConnectionTask.class.getName() + "初始化");
    }

    @Override
    public void run() {
        while (true) {
            try {
                handle();
            } catch (Exception e) {
                e.printStackTrace();
                Other.sleep(10000);
            }
        }
    }

    private void handle() throws Exception {
        while (true) {
            String poll = linkedList.poll();
            if (poll == null) {
                synchronized (linkedList) {
                    poll = linkedList.poll();
                    if (poll == null) {
                        linkedList.wait();
                        continue;
                    }
                }
            }
            ServerAttr serverAttr = serverManager.get(poll);
            if (serverAttr == null || serverAttr.getStatus() == ServerAttr.status_3) {
                continue;
            }
            serverAttr.setStatus(ServerAttr.status_2);
            connection(serverAttr);
        }
    }

    private void connection(ServerAttr serverAttr) {
        switch (serverAttr.getType()) {
            case ServerAttr.type_1:
                connectionPublic(serverAttr);
                break;
			case ServerAttr.type_0:
				connectionNun(serverAttr);
				break;
            default:
                break;
        }
    }

	@Autowired
	private PerHandleTask perHandleTask;


	/**
	 * 连接未知类型 1，向来源询问是否可建立双向链接
	 * 
	 * @param serverAttr
	 */
	private void connectionNun(ServerAttr serverAttr) {
		perHandleTask.add(new PerHandleType().setType(3).setServerAttr(serverAttr).setPer(serverAttr.getAddress()));
	}

	/**
	 * 公网服务器的连接
	 *
	 * @param serverAttr
	 * @author 木鬼
	 */
    private void connectionPublic(ServerAttr serverAttr) {
        if (!server.pingWaitRet(serverAttr, 10000)) {
            serverAttr.setStatus(ServerAttr.status_0);
            dao.updata(serverAttr);
//            serverManager.del(serverAttr.getAddress());
            System.out.println("公网：" + serverAttr.toString() + " 连接失败");
            return;
        }
        serverAttr.setStatus(ServerAttr.status_3);
        if (serverAttr.getId() != null) {
            dao.updata(serverAttr);
        } else {
            dao.save(serverAttr);
        }
        System.out.println("公网：" + serverAttr.toString() + " 连接成功");
        keepConnectionTask.add(serverAttr.getAddress());
    }
    
    @Autowired
    private KeepConnectionTask keepConnectionTask;
    
   

    public void add(String key) {
        synchronized (linkedList) {
            linkedList.add(key);
            linkedList.notifyAll();
        }
    }
}
